""""进程池中的queue，如果使用Pool创建子进程，则需要使用multiprocessing.Manager()中的Queue()，而不是multiprocessing.Queue()"""
from multiprocessing import Pool, Manager
import os, time, random


def process_read(queue):
    print("Child process_read {} start, the parent process is {}".format(os.getpid(), os.getppid()))
    while True:
        if not queue.empty():
            print("Get message from Queue:{}".format(queue.get(True)))
        else:  # 如果queue是空，有可能是还没写完，等一秒再判断一下，如果还是这样，那我就退出了
            time.sleep(1)
            if queue.empty():
                break


def process_write(queue):
    print("Child process_write {} start, the parent process is {}".format(os.getpid(), os.getppid()))
    for i in ["I love python", 123, True, 3.5, "laozhao"]:
        if not queue.full():
            queue.put_nowait(i)
            time.sleep(random.random())
        else:
            print("The queue is full")


if __name__ == "__main__":
    queue = Manager().Queue()
    pool = Pool()

    pool.apply_async(process_write, (queue,))
    pool.apply_async(process_read, (queue,))

    pool.close()
    pool.join()
